package com.itshizhan.itjidancideveloper.controller.ucenter

import com.itshizhan.itjidancideveloper.dao.ucenter.WordDao
import com.itshizhan.itjidancideveloper.models.Word
import com.itshizhan.itjidancideveloper.response.CodeMsgEnum
import com.itshizhan.itjidancideveloper.response.Response
import com.itshizhan.itjidancideveloper.utils.DateUtils
import org.springframework.web.bind.annotation.*
import java.util.*

@RestController()
@RequestMapping("/ucenter/word")
class WordController(private val wordDao: WordDao) {

  @GetMapping("/test")
  fun hellTest(): String {
    return "Hello Springboot with Kotlin"
  }

  @GetMapping("/search")
  fun getListByKeyword(@RequestParam("q") keyword: String): Response<MutableList<Word>> {
    println("keyword = [${keyword}]")
    if (keyword.length < 3) {
      return Response.code(CodeMsgEnum.ERROR_PARAMETER)
    }
    return Response.success(wordDao.findByWordNameLike(keyword))
  }

  @GetMapping("/detail")
  fun getWordDetailById(@RequestParam("id") id: Long): Response<Optional<Word>> {
    val word = wordDao.findById(id)
    //println("getWordDetailById==$word")
    return Response.success(word)

  }

  @PostMapping("/save")
  fun saveWord(@RequestBody word: Word): Response<Word> {
    println("saveWord=${word.id}")
    val dbWord = wordDao.findById(word.id).orElse(null)
    println("dbWord==$dbWord")
    if (dbWord!=null){
      dbWord.memoryMd = word.memoryMd;
      dbWord.memoryHtml = word.memoryHtml;
      val save = wordDao.save(dbWord)
      return Response.success(word)
    }
    return Response.fail(CodeMsgEnum.SAVE_FAIL.msg)

  }
}